import { cloneDeep, set, get } from 'lodash';
import { getCurrentUser } from '@/utils/user';

// 转化列表选中的数据  -  转换协助人
export const transferFormValues = (originObj = {}) => {
  const helpPersonsStrs = (originObj.helpPersonsStr || '').split(',');
  const showSelpPersonsStr = helpPersonsStrs.join(',');
  return {
    ...originObj,
    helpPersonsStr: showSelpPersonsStr,
  };
};

// 静态的改变选中行的数据，而不刷新列表 (默认只改变选中的第一行)
export const staticChangeRow = ({ gridManagerRef, selectedRows = [], changeObj = {}, length = 1 }) => {
  gridManagerRef.current
    ?.modify(
      selectedRows.slice(0, length).map((item) => {
        const newItem = cloneDeep(item);
        for (const [key, value] of Object.entries(changeObj)) {
          set(newItem, key, value);
        }
        return newItem;
      }),
    )
    .then(() => {
      const dataSource = gridManagerRef.current?.getPureData();
      gridManagerRef.current.save(async () => dataSource);
    });
  // 去选所有选中
  gridManagerRef.current?.agGridApi?.deselectAll?.();
};

// 检验是否为权限人
export function checkIsOwner(row: any, ownerFieldName = '') {
  const currentUser = getCurrentUser();
  const ownerId = get(row, ownerFieldName);
  return ownerId === currentUser.id;
}

// 检测当前用户是否未管理员
export function checkIsAdmin() {
  return getCurrentUser()?.userLoginName === 'admin';
}

// 校验当前登陆人是否在指定人的范围内 --- 责任人和mbom工程师都可以下发
export function checkIsAuher(row: any) {
  if (checkIsAdmin()) {
    return true;
  }
  const currentUser = getCurrentUser();
  const owner = get(row, 'owner') || '';
  const authPersonsStr = get(row, 'authPersonsStr') || '';
  const authersList = [...owner.split(','), ...authPersonsStr.split(',')];
  return authersList.includes(currentUser.id);
}
